import paho.mqtt.client as mqtt
import re

HOST = "douzi.wiki"
PORT = 1883
humidity = 60
temperature = 26
illuminance = 120
is_nobody = True
is_nobody_count = 0


def on_message_callback(client, userdata, message):
    global humidity
    global temperature
    global illuminance
    global is_nobody
    global is_nobody_count

    # 回报数据格式化
    print(message.topic + " " + ":" + str(message.payload))
    data = re.findall("b'(.+?)'", str(message.payload))
    print(data)

    # 判断人物数量数据
    if message.topic == "/classroom/105/motion":
        if data == ['person']:
            is_nobody = False
        else:
            is_nobody = True
            is_nobody_count += 1
            if is_nobody_count == 5:
                client.publish("/classroom/105/light_1", "off", 0)
                client.publish("/classroom/105/humidifier", "off", 0)
            if is_nobody_count == 10:
                client.publish("/classroom/105/airConditioner", "off", 0)
            if is_nobody_count == 1440:
                is_nobody_count = 20

    # 开门后教室设备控制
    if message.topic == "/classroom/105/accessControl":
        if data == ['on']:
            # 没人的情况下
            if is_nobody:
                client.publish("/classroom/105/airConditioner", "on", 0)
                if illuminance <= 300:
                    client.publish("/classroom/105/light_1", "on", 0)

    # 储存光照数据
    if message.topic == "/classroom/105/illuminance":
        illuminance = float(data[0])
        print(illuminance)
    # 储存温湿度数据
    if message.topic == "/classroom/105/humiture":
        humiture_data = data[0].split("#", 2)
        humidity = float(humiture_data[1])
        temperature = float(humiture_data[2])

    if not is_nobody:
        # 加湿器自动控制
        print(humidity)
        if humidity <= 45:
            print("湿度小于45%，打开加湿器。")
            client.publish("/classroom/105/humidifier", "on", 0)
        if humidity >= 75:
            print("湿度大于75%，关闭加湿器。")
            client.publish("/classroom/105/humidifier", "off", 0)


def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("/classroom/105/humiture")
    client.subscribe("/classroom/105/illuminance")
    client.subscribe("/classroom/105/accessControl")
    client.subscribe("/classroom/105/motion")


def main():
    client = mqtt.Client('test')
    client.connect(HOST, PORT, 60)
    client.on_connect = on_connect
    client.publish("/classroom/105/serverStatus", "计算模块上线", 1)
    client.on_message = on_message_callback
    client.loop_forever()


if __name__ == '__main__':
    print('服务器上线')
    main()
